// 保存经期周期信息云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const userId = wxContext.OPENID
  
  try {
    const { startDate, periodDates, year, month } = event
    
    console.log('保存经期周期信息:', {
      userId,
      startDate,
      periodDates,
      year,
      month
    })

    const now = new Date()
    
    // 构建周期数据
    const cycleData = {
      user_id: userId,
      start_date: startDate,
      period_dates: periodDates,
      year: year,
      month: month,
      created_at: now,
      updated_at: now
    }

    // 检查是否已存在该月的经期周期
    const existingCycle = await db.collection('period_cycles')
      .where({
        user_id: userId,
        year: year,
        month: month
      })
      .get()

    if (existingCycle.data.length > 0) {
      // 更新现有周期
      const cycleId = existingCycle.data[0]._id
      
      await db.collection('period_cycles')
        .doc(cycleId)
        .update({
          data: {
            start_date: startDate,
            period_dates: periodDates,
            updated_at: now
          }
        })
      
      console.log('更新经期周期成功:', cycleId)
      
      return {
        status: 'success',
        message: '经期周期更新成功',
        data: {
          _id: cycleId,
          action: 'updated'
        }
      }
    } else {
      // 创建新周期
      const result = await db.collection('period_cycles')
        .add({
          data: cycleData
        })
      
      console.log('创建经期周期成功:', result._id)
      
      return {
        status: 'success',
        message: '经期周期创建成功',
        data: {
          _id: result._id,
          action: 'created'
        }
      }
    }

  } catch (error) {
    console.error('保存经期周期失败:', error)
    return {
      status: 'error',
      message: '保存经期周期失败',
      error: error.message
    }
  }
}
